;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.ReturnApply", [])
        .controller("ReturnApplyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus) {
            $scope.activeFlag = [true, false, false, false, false, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.sellPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.orderCondition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.sellList = [];
            $scope.detailInfo = {};
            $scope.detailInfo.returnApplyDetailVOs = [];
            $scope.detailInfo.payConditionCode = 1;
            $scope.steps = {
                curStep: 0,
                list: [{name: '选择销售意向单'}, {name: '提交退货申请'}]
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/returnApply/export"),
                sectionParam: {returnInIds: []},
                allUrl: ybHttp.RequestUrl("device", "/returnApply/exportAll")
            };
            $scope.tbConf = {
                fixedWidth: 180,
                scrollWidth: 1500,
                tableCol: [
                    {
                        type: "",
                        name: "申请单号",
                        dataField: "applyNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购公司",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "createDateShows",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "退货申请状态",
                        dataField: "isReturnDesc",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "退货入库状态",
                        dataField: "isInDesc",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "statusDesc",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第一步审核人",
                        dataField: "auditName",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第一步审核时间",
                        dataField: "auditDateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第二步审核人",
                        dataField: "secondAuditName",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第二步审核时间",
                        dataField: "secondAuditDateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditDesc",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 140,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.sellTbConf = {
                scrollWidth: 1210,
                tableCol: [
                    {
                        type: "",
                        name: "意向单号",
                        dataField: "saleNo",
                        width: 180
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 200
                    },
                    {
                        type: "",
                        name: "采购单号",
                        dataField: "purchaseNo",
                        width: 120
                    },
                    {
                        type: "",
                        name: "采购级别",
                        dataField: "purchaseLevelName",
                        width: 100
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "deliverTypeName",
                        width: 100
                    },
                    {
                        type: "",
                        name: "创建方式",
                        dataField: "createTypeShow",
                        width: 100
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 100
                    },
                    {
                        type: "",
                        name: "创建日期",
                        dataField: "createDateShow",
                        width: 100
                    },
                    {
                        type: "",
                        name: "发货通知状态",
                        dataField: "deliverStatusShow",
                        width: 110
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "inventoryOutStatusShow",
                        width: 100
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80
                    }
                ]
            };
            $scope.newTbConf = {
                scrollWidth: 800,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已退货数量",
                        width: 100,
                        dataField: "returnApplyAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可退货数量",
                        width: 100,
                        dataField: "lastQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "打折接收金额",
                        width: 100,
                        dataField: "priceDiscount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.manulTbConf = {
                scrollWidth: 1000,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: true,
                        inputType: "price"
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "打折接收金额",
                        width: 100,
                        dataField: "priceDiscount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.editTbConf = {
                scrollWidth: 820,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已退货数量",
                        width: 100,
                        dataField: "returnApplyAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可退货数量",
                        width: 100,
                        dataField: "lastQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "检验合格数量",
                        width: 110,
                        dataField: "checkOutNum",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "打折接收金额",
                        width: 120,
                        dataField: "priceDiscount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.manulEditTbConf = {
                scrollWidth: 780,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 120,
                        dataField: "priceSchemeName",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: true,
                        inputType: "price"
                    },
                    {
                        name: "检验合格数量",
                        width: 110,
                        dataField: "checkOutNum",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "打折接收金额",
                        width: 120,
                        dataField: "priceDiscount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.viewTbConf = {
                scrollWidth: 700,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已退货数量",
                        width: 100,
                        dataField: "returnApplyAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "检验合格数量",
                        width: 110,
                        dataField: "checkOutNum",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已入库数量",
                        width: 100,
                        dataField: "inQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "打折接收金额",
                        width: 120,
                        dataField: "priceDiscount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: false,
                        inputType: ""
                    }
                ]
            };
            $scope.manulViewTbConf = {
                scrollWidth: 700,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "检验合格数量",
                        width: 110,
                        dataField: "checkOutNum",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已退货数量",
                        width: 100,
                        dataField: "returnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已入库数量",
                        width: 100,
                        dataField: "inQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "打折接收金额",
                        width: 120,
                        dataField: "priceDiscount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: false,
                        inputType: ""
                    }
                ]
            };
            $scope.auditTbConf = {
                scrollWidth: 720,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已退货数量",
                        width: 100,
                        dataField: "returnApplyAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "检验合格数量",
                        width: 110,
                        dataField: "checkOutNum",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "打折接收金额",
                        width: 120,
                        dataField: "priceDiscount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.manulAuditTbConf = {
                scrollWidth: 920,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "采购数量",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "检验合格数量",
                        width: 110,
                        dataField: "checkOutNum",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "退货数量",
                        width: 100,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "打折接收金额",
                        width: 120,
                        dataField: "priceDiscount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "折扣",
                        width: 100,
                        dataField: "discount",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.tabFlag = {};
            var sortParam = "";
            var sortFiled = {};
            var tabFlag = {
                0: "新增退货申请",
                1: "手动新增退货申请",
                2: "采购申请详情",
                3: "编辑采购申请"
            };
            $scope.stateList = [
                {id: 0, name: "待审核"},
                {id: 1, name: "审核拒绝"},
                {id: 2, name: "审核通过"},
            ];
            $scope.returnState = [
                {id: 0, name: "未退货"},
                {id: 1, name: "部分退货"},
                {id: 2, name: "全部退货"},
            ];
            $scope.inState = [
                {id: 0, name: "未入库"},
                {id: 1, name: "入库中"},
                {id: 2, name: "入库完成"},
            ];

            var btnPermissionCode = {
                returnApplyAdd: window.ActionCode.returnApplyAdd,
                returnApplyManulAdd: window.ActionCode.returnApplyManulAdd,
                returnApplyDel: window.ActionCode.returnApplyDel,
                returnApplyEdit: window.ActionCode.returnApplyEdit,
                returnApplyAudit: window.ActionCode.returnApplyAudit,
                returnApplyPrint: window.ActionCode.returnApplyPrint,
                returnApplyExport: window.ActionCode.returnApplyExport
            };

            $scope.btnPermission = {
                returnApplyAdd: true,
                returnApplyManulAdd: true,
                returnApplyDel: true,
                returnApplyEdit: true,
                returnApplyAudit: true,
                returnApplyPrint: true,
                returnApplyExport: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tbConf.fixedWidth + "px"}
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    case 5:
                        break;
                    case 6:
                        break;
                    case 7:
                        break;
                    case 8:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {};
                $scope.detailInfo.returnApplyDetailVOs = [];
                $scope.steps.curStep = 0;
                $scope.toolbarConfig.showMateriel = false;
                $scope.markInfo.allCheckedMaterial = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allChecked: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.returnInIds = [];
                var service = "device";
                var reqUrl = "/returnApply/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
						item.auditDateShow = $filter("YbDate")(item.auditDate,'yyyy-MM-dd HH:mm:ss');
                        item.createDateShow = $filter("YbDate")(item.createDate,'yyyy-MM-dd HH:mm:ss');
                        item.secondAuditDateShow = $filter("YbDate")(item.secondAuditDate,'yyyy-MM-dd HH:mm:ss');
                        item.createDateShows = $filter("YbDate")(item.createDate,'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                return;
                if (!config[index].toSort) {
                    return;
                }
                var sortType = ybWidget.ToSort(config, index);
                sortFiled = config[index];
                sortParam = sortFiled.sortField + " " + sortType;
                getDataList(1);
            };

            function clearSortParam() {
                sortParam = "";
                if (angular.isDefined(sortFiled.sortType)) {
                    sortFiled.sortType = ""
                }
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            function geBillIds() {
                $scope.exportParam.sectionParam.returnInIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.returnInIds.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
                geBillIds();
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.detailInfo.returnApplyDetailVOs.length; i < len; i++) {
                    if (!$scope.detailInfo.returnApplyDetailVOs[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                geBillIds();
            };

            $scope.selectAllDetail = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                getSellList();
                $scope.changeTab(1);
            };

            $scope.manulAddApply = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(5);
            };

            function getSellList(curPage) {
                var service = "device";
                var reqUrl = "/saleIntention/list";
                var param = {};
                param.pageSize = $scope.sellPageInfo.pageSize;
                if (!!curPage) {
                    $scope.sellPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.sellPageInfo.curPage;
                param.filters = {};
                param.filters.purchaseOrgName = $scope.orderCondition.purchaseOrgName;
                param.filters.status = $scope.orderCondition.status;
                param.createDateStart=$scope.condition.createDateStart,
                param.createDateEnd=$scope.condition.createDateEnd,
                param.filters.isReturn = 0;
                param.filters.deliverStatusTemp = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createTypeShow = $filter("CreateWay")(item.createType);
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.deliverStatusShow = $filter("ProgressStatus")(item.deliverStatus);
                        item.inventoryOutStatusShow = $filter("ProgressStatus")(item.inventoryOutStatus, "outDepot");
                    });
                    $scope.sellPageInfo.totalRows = resp.value.total;
                    $scope.sellPageInfo.totalPages = resp.value.pages;
                    $scope.sellList = resp.value.list;
                });
            }

            $scope.selSell = function (item) {
                $scope.steps.curStep = 1;
                $scope.detailInfo.returnApplyDetailVOs = [];
                ybHttp.Get('device', '/saleIntention/itemSaleInfo', {id: item.id}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.saleNo = resp.value.headerInfo.saleNo;
                    $scope.detailInfo.supplierOrgId = resp.value.headerInfo.supplierOrgId;
                    $scope.detailInfo.supplierOrgName = resp.value.headerInfo.supplierOrgName;
                    $scope.detailInfo.purchaseOrgId = resp.value.headerInfo.purchaseOrgId;
                    $scope.detailInfo.purchaseOrgName = resp.value.headerInfo.purchaseOrgName;
                    $scope.detailInfo.salesmanName = resp.value.headerInfo.createName;

                    angular.forEach(resp.value.materialList, function (item) {
                        var materielItem = {};
                        materielItem.materialsNo = item.materialsNo;
                        materielItem.materialsDes = item.materialsDes;
                        materielItem.unit = item.unit;
                        materielItem.qty = item.amountAfterAdjust;
                        materielItem.returnApplyAmount = item.returnApplyAmount;
                        materielItem.applyQty = ybWidget.Minus(item.amountAfterAdjust, item.returnApplyAmount);
                        materielItem.lastQty = ybWidget.Minus(item.amountAfterAdjust, item.returnApplyAmount);
                        materielItem.priceSchemeId = item.priceSchemeId;
                        materielItem.priceSchemeName = item.priceSchemeName;
                        materielItem.price = item.unitPriceAfterAdjust;
                        $scope.detailInfo.returnApplyDetailVOs.push(materielItem);
                    });

                });
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.orderSearch = function () {
                getSellList();
            };

            $scope.checkQty = function (item,dataField) {
                item['qtyErr'+dataField]=false;
                if(dataField==="applyQty"){
                    if(!item['applyQty']){
                        item['qtyErr'+dataField] = true;
                        item['qtyErrMsg'+dataField] = "退货数量不能为空！";
                        return;
                    }
                }

                if (parseFloat(item.applyQty) > parseFloat(item.lastQty)) {
                    item['qtyErr'+dataField]  = true;
                    item['qtyErrMsg'+dataField] = "退货数量不能大于可退货数量！";
                }
            };
            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.delData = function (delType, billId) {
                var service = "device";
                var reqUrl = "/returnApply/remove";
                var billIds = [];

                if (delType === "single") {
                    billIds.push(billId);
                }

                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            billIds.push($scope.dataList[i].id);
                        }
                    }
                }

                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, billIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/returnApply/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.editApply = function (item) {
                $scope.tabFlag.type = 1;
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.returnApplyDetailVOs, function (item) {
                        item.lastQty = ybWidget.Plus(ybWidget.Minus(item.qty, item.returnApplyAmount), item.applyQty);
                        if(!item.checkOutNum){
                            item.checkOutNum = 0;
                        }
                    });
                    if(!!data.saleNo){
                        $scope.changeTab(4);
                    }else{
                        $scope.changeTab(7);
                    }
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    angular.forEach(data.returnApplyDetailVOs, function (item) {
                        if(!item.checkOutNum){
                            item.checkOutNum = 0;
                        }
                    });
                    $scope.detailInfo = data;
                    if(!!data.saleNo){
                        $scope.changeTab(3);
                    }else{
                        $scope.changeTab(6);
                    }
                });
            }

            $scope.auditApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    angular.forEach(data.returnApplyDetailVOs, function (item) {
                        if(!item.checkOutNum){
                            item.checkOutNum = item.applyQty;
                        }
                    });
                    $scope.detailInfo = data;
                    if(!!data.saleNo){
                        $scope.changeTab(2);
                    }else{
                        $scope.changeTab(8);
                    }
                });
            };

            function checkListValid() {
                var isValid = true;
                for (var i = 0, len = $scope.detailInfo.returnApplyDetailVOs.length; i < len; i++) {
                    if ($scope.detailInfo.returnApplyDetailVOs[i].applyQty === "") {
                        ybWidget.ShowToaster("error", "退货数量不能为空！");
                        isValid = false;
                        break;
                    }
                    if (!$scope.detailInfo.returnApplyDetailVOs[i].price || parseFloat($scope.detailInfo.returnApplyDetailVOs[i].price) === 0) {
                        ybWidget.ShowToaster('error', '单价不能为空和0！');
                        isValid = false;
                        break;
                    }
                    if (parseFloat($scope.detailInfo.returnApplyDetailVOs[i].applyQty) > parseFloat($scope.detailInfo.returnApplyDetailVOs[i].lastQty)) {
                        ybWidget.ShowToaster('error', '退货数量不能大于可退货数量！');
                        isValid = false;
                        break;
                    }
                }
                return isValid;
            }

            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    if (!!$scope.detailInfo.purchaseOrgId && (data.dealerOrgId !== $scope.detailInfo.purchaseOrgId)) {
                        clearPriceScheme();
                        clearMateriel()
                    }
                    $scope.detailInfo.purchaseOrgName = data.companyName;
                    $scope.detailInfo.purchaseOrgId = data.dealerOrgId;
                })
            };

            function clearMateriel() {
                $scope.detailInfo.returnApplyDetailVOs = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    if (!$scope.detailInfo.purchaseOrgId) {
                        EventBus.Publish("clearMaterial");
                    } else {
                        EventBus.Publish("getMaterial");
                    }
                });
            }

            function clearPriceScheme() {
                angular.forEach($scope.detailInfo.returnApplyDetailVOs, function (item) {
                    item.priceSchemeId = "";
                    item.priceSchemeName = "";
                    item.price = item.sourcePrice;
                });
            }

            $scope.clearPriceScheme = function (item) {
                item.priceSchemeId = "";
                item.priceSchemeName = "";
                item.price = item.sourcePrice;
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    if (!$scope.detailInfo.purchaseOrgName) {
                        ybWidget.ShowToaster('error', '请选择采购公司');
                        return;
                    }
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                if (!$scope.detailInfo.purchaseOrgName) {
                    ybWidget.ShowToaster('error', '请选择采购公司');
                    return;
                }
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/returnApply/download",
                    importReqService: "device",
                    importReqUrl: "/returnApply/import",
                    importErrorUrl: "",
                    dealerOrgId:$scope.detailInfo.purchaseOrgId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.detailInfo.returnApplyDetailVOs = [];
                    $scope.detailInfo.returnApplyDetailVOs = angular.copy(data);
                });
            };

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.detailInfo.returnApplyDetailVOs.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.detailInfo.returnApplyDetailVOs.length; i < len; i++) {
                    if (!!$scope.detailInfo.returnApplyDetailVOs[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.detailInfo.returnApplyDetailVOs.length - 1; i >= 0; i--) {
                        if (!!$scope.detailInfo.returnApplyDetailVOs[i].isChecked) {
                            $scope.detailInfo.returnApplyDetailVOs.splice(i, 1);
                        }
                    }
                    if ($scope.detailInfo.returnApplyDetailVOs.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.chosePriceScheme = function (item, index) {
                var clientId = $scope.detailInfo.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                var param = {
                    schemeType: 0,
                    apiObj: {
                        param: {
                            dealerOrgId: clientId,
                            materialsNo: item.materialsNo
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    setPriceScheme(item, index, data);
                })
            };

            function setPriceScheme(item, index, priceScheme) {
                item.priceSchemeId = priceScheme.activityId;
                item.priceSchemeName = priceScheme.name;

                $scope.detailInfo.returnApplyDetailVOs[index].price = $filter("decimalCover")(priceScheme.discountPrice, 2);
            }

            /**
             * 批量选择价格方案
             */
            $scope.batchChosePriceScheme = function() {
                var clientId = $scope.detailInfo.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }
                
                var param = {
                    isBatch: true,
                    schemeType: 0,
                    apiObj: {
                        param: {
                            dealerOrgId: clientId,
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    batchSetPriceScheme(data.id);
                });
            };

            /**
             * 批量设置价格方案
             * @param priceSchemeId 价格方案标志
             */
            function batchSetPriceScheme(priceSchemeId) {
                for (var i = 0; i < $scope.detailInfo.returnApplyDetailVOs.length; i++) {
                    var materialItem = $scope.detailInfo.returnApplyDetailVOs[i];
                    var priceSchemeList = materialItem.marketingActivityPriceVOList || [];
                    var priceScheme = getPriceScheme(priceSchemeId, priceSchemeList);
                    if (priceScheme != null) {
                        setPriceScheme(materialItem, i, priceScheme);
                    }
                }

                function getPriceScheme(id, list) {
                    for (var j = 0; j < list.length; j++) {
                        if (id == list[j].activityId) {
                            return list[j];
                        }
                    }
                    return null;
                }
            }

            $scope.setAdjustPrice = function (item, colItem) {
                setAdjustPrice(item, colItem)
            };

            function setAdjustPrice(item, colItem) {
                item.priceAdjustErr = false;
                if (!item.applyQty || parseFloat(item.applyQty)<=0) {
                    item.qtyAdjustErr = true;
                }
                if (!item.price || parseFloat(item.price)<=0) {
                    item.priceAdjustErr = true;
                }
                if(item.applyQty>99999.999){
                    item.applyQty=99999.999;
                }
            }

            $scope.saveData = function (invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = checkListValid();

                if (!listValid) {
                    return;
                }
                var service = "device";
                var reqUrl = "/returnApply/add";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/returnApply/update";
                }
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };
            $scope.manulSaveData = function (invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = checkListValid();

                if (!listValid) {
                    return;
                }
                var service = "device";
                var reqUrl = "/returnApply/manulAdd";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/returnApply/manulUpdate";
                }
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };
            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "ReturnApply"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };
            $scope.auditPurchase = function (type, item) {
                var service = "device";
                var reqUrl = "/returnApply/audit";
                if(!item.saleNo){
                    reqUrl = "/returnApply/manulAudit";
                }
                item.auditStatus = 2;
                if (type === "refuse") {
                    if (!item.auditDesc) {
                        ybWidget.ShowMessage('请输入审核意见');
                        $scope.submitted = true;
                        return;
                    }
                    item.auditStatus = 1;
                }

                ybHttp.Post(service, reqUrl, item).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.prevStep = function () {
                $scope.steps.curStep = 0;
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);